const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const srcDir = path.join(__dirname, "src");

module.exports = {
  mode: "production",
  entry: {
    sidebar: path.join(srcDir, "sidebar/index.tsx"),
    options: path.join(srcDir, "options/index.tsx"),
    background: path.join(srcDir, "background/index.ts"),
    content_script: path.join(srcDir, "content/index.ts"),
  },
  output: {
    path: path.join(__dirname, "dist/js"),
    filename: "[name].js",
    charset: true, // 确保输出文件使用正确的字符编码
    clean: true, // 清理输出目录
  },
  optimization: {
    splitChunks: {
      name: "vendor",
      chunks(chunk) {
        return chunk.name !== "background";
      },
    },
    // 优化中文字符处理
    minimize: true,
    usedExports: true,
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: {
          loader: 'ts-loader',
          options: {
            // 使用项目的tsconfig.json配置
            configFile: 'tsconfig.json',
            // 优化构建性能
            transpileOnly: false,
          }
        },
        exclude: /node_modules/,
      },
      // 添加CSS处理支持
      {
        test: /\.css$/i,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              // 支持CSS模块
              modules: {
                auto: true,
                localIdentName: '[name]__[local]--[hash:base64:5]',
              },
              // 确保CSS中的中文字符正确处理
              importLoaders: 1,
            },
          },
        ],
      },
      // 字体文件处理
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',
        generator: {
          filename: 'fonts/[name][ext]',
        },
      },
    ],
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".css"],
    // 添加路径别名，便于引用
    alias: {
      '@': srcDir,
      '@components': path.join(srcDir, 'components'),
      '@services': path.join(srcDir, 'services'),
      '@types': path.join(srcDir, 'types'),
    },
  },
  plugins: [
    new CopyWebpackPlugin({
      patterns: [
        { 
          from: "public", 
          to: "../",
          // 确保复制时保持文件编码
          globOptions: {
            ignore: ['**/.DS_Store'],
          },
        }
      ],
      options: {},
    }),
  ],
  // 开发体验优化
  stats: {
    children: false,
    modules: false,
    entrypoints: false,
  },
  // 性能配置
  performance: {
    hints: 'warning',
    maxAssetSize: 2000000, // 2MB
    maxEntrypointSize: 2000000, // 2MB
  },
};
